package com.cz.background.common.config;

import com.cz.background.common.dto.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.cz.background.controller")
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 判断是否需要执行beforeBodyWrite方法
     *
     * @param returnType    方法返回值类型
     * @param converterType 转换器类型
     * @return 是否执行响应体处理
     */
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除一些不需要处理的类型，如已经是统一响应体的
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return ResponseResult.success("success", body);
    }

}

